import json
import os
import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import secrets
from typing import Dict, Any, Optional
import logging

class APIConfigManager:
    def __init__(self, config_file: str = "api_config.json", key_file: str = ".encryption_key"):
        self.config_file = config_file
        self.key_file = key_file
        self.fernet = self._initialize_encryption()
        self.config = self._load_config()
        
    def _initialize_encryption(self) -> Fernet:
        """初始化加密密钥"""
        if os.path.exists(self.key_file):
            with open(self.key_file, 'rb') as f:
                key = f.read()
        else:
            # 生成新密钥
            password = secrets.token_bytes(32)
            salt = secrets.token_bytes(16)
            kdf = PBKDF2HMAC(
                algorithm=hashes.SHA256(),
                length=32,
                salt=salt,
                iterations=100000,
            )
            key = base64.urlsafe_b64encode(kdf.derive(password))
            with open(self.key_file, 'wb') as f:
                f.write(key)
        
        return Fernet(key)
    
    def _load_config(self) -> Dict[str, Any]:
        """加载API配置"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r') as f:
                    encrypted_data = f.read()
                decrypted_data = self.fernet.decrypt(encrypted_data.encode())
                return json.loads(decrypted_data)
            except Exception as e:
                logging.error(f"Failed to load API config: {e}")
                return self._get_default_config()
        return self._get_default_config()
    
    def _get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            "providers": {
                "openai": {
                    "enabled": True,
                    "base_url": "https://api.openai.com/v1",
                    "default_model": "gpt-4",
                    "max_tokens": 500,
                    "temperature": 0.7,
                    "rate_limit": 60,  # 每分钟最大请求数
                    "concurrent_requests": 5  # 最大并发请求数
                },
                "free_ai": {
                    "enabled": True,
                    "base_url": "https://api-inference.huggingface.co",
                    "fallback_enabled": True,
                    "rate_limit": 30
                }
            },
            "security": {
                "encrypt_api_keys": True,
                "key_rotation_days": 30,
                "audit_log_enabled": True
            },
            "monitoring": {
                "health_check_interval": 300,  # 5分钟
                "timeout_seconds": 30,
                "retry_attempts": 3
            }
        }
    
    def save_config(self) -> bool:
        """保存配置到文件"""
        try:
            config_json = json.dumps(self.config, indent=2)
            encrypted_data = self.fernet.encrypt(config_json.encode())
            with open(self.config_file, 'w') as f:
                f.write(encrypted_data.decode())
            return True
        except Exception as e:
            logging.error(f"Failed to save API config: {e}")
            return False
    
    def get_provider_config(self, provider: str) -> Optional[Dict[str, Any]]:
        """获取特定提供商配置"""
        return self.config["providers"].get(provider)
    
    def update_provider_config(self, provider: str, updates: Dict[str, Any]) -> bool:
        """更新提供商配置"""
        if provider not in self.config["providers"]:
            return False
        
        self.config["providers"][provider].update(updates)
        return self.save_config()
    
    def encrypt_api_key(self, api_key: str) -> str:
        """加密API密钥"""
        return self.fernet.encrypt(api_key.encode()).decode()
    
    def decrypt_api_key(self, encrypted_key: str) -> str:
        """解密API密钥"""
        return self.fernet.decrypt(encrypted_key.encode()).decode()
    
    def validate_api_key(self, provider: str, api_key: str) -> bool:
        """验证API密钥有效性"""
        if provider == "openai":
            return self._validate_openai_key(api_key)
        elif provider == "free_ai":
            return self._validate_freeai_key(api_key)
        return False
    
    def _validate_openai_key(self, api_key: str) -> bool:
        """验证OpenAI API密钥"""
        try:
            import openai
            openai.api_key = api_key
            models = openai.Model.list()
            return len(models.data) > 0
        except Exception:
            return False
    
    def _validate_freeai_key(self, api_key: str) -> bool:
        """验证免费API密钥"""
        # 格式验证
        return len(api_key) > 10  # 长度检查